package plenprojects.model;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import plenprojects.exceptions.ConversionException;

public class ChatMessage {
	
	private String message;
	private String username;
	private String time;
	
	public ChatMessage() {}
	
	public ChatMessage(String message, String username, String time) {
		
		this.message = message;
		this.username = username;
		this.time = time;
	}

	public String getMessage() {
		
		return message;
	}
	
	public void setMessage(String message) {
		
		this.message = message;
	}
	
	public String getUsername() {
		
		return username;
	}
	
	public void setUsername(String username) {
		
		this.username = username;
	}
	
	public String getTime() {
		
		return time;
	}
	
	public void setTime(String time) {
		
		this.time = time;
	}
	
	public static ChatMessage fromMap(Map<String, String> map) throws ConversionException {
		
		ChatMessage msg = new ChatMessage();
		
		msg.setMessage(ChatMessage.extract("message", map));
		msg.setUsername(ChatMessage.extract("username", map));
		msg.setTime(ChatMessage.extract("time", map));
		
		return msg;
	}
	
	public static String dateToString(Date date) {
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		return dateFormat.format(date);
		
	}
	
	public Map<String, String> convertToMap() {
		
		Map<String, String> map = new HashMap<String, String>();
		
		map.put("username", this.username);
		map.put("message", this.message);
		map.put("time", this.time);
		
		return map;
	}
	
	private static String extract(String what, Map<String, String> map) throws ConversionException {
		
		String thing = null;
		
		thing = map.get(what);
		
		if(thing == null) {
			
			throw new ConversionException("Parameter " + what + " not set.");
		}
		
		return thing;
		
	}

	@Override
	public String toString() {
		
		return this.message + ":" + this.username + ":" + this.time;
	}
	
}